package com.cms.portal.security.realm;

import com.cms.dao.enums.UserStatusEnum;
import com.cms.service.api.IUserPrimaryService;
import com.cms.service.api.IUserService;
import com.cms.service.dto.UserDto;
import com.cms.service.dto.UserPrimaryDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.apache.shiro.util.SimpleByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Objects;

/**
 * @author laolang
 * @version 1.0.0
 * @ClassName UsernamePasswordCaptchaRealm
 */
@Slf4j
public class UsernamePasswordCaptchaRealm extends AuthorizingRealm {

    @Autowired
    private IUserService userService;
    @Autowired
    private IUserPrimaryService userPrimaryService;

    /**
     * 认证
     *
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取用户名
        String  username = (String) token.getPrincipal();

        //从副表中查找用户是否存在
        UserDto userDto = userService.findByUsername(username);

        // 判断用户是否存在
        if(Objects.isNull(userDto)){
            throw  new UnknownAccountException();
        }
        //校验用户是否禁用
        verifyStatus(userDto.getStatus());
        //查询主表用户信息
        UserPrimaryDto userPrimaryDto = userPrimaryService.getById(userDto.getId());
        //查询盐值
        ByteSource byteSource = new SimpleByteSource(userPrimaryDto.getSalt());
        //匹配用户信息
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(userDto, userPrimaryDto.getPassword(), byteSource, getName());

        return simpleAuthenticationInfo;
    }


    /**
     * 授权
     *
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        return null;
    }

    /**
     * 校验用户状态
     * @param userStatusEnum
     */
    private void verifyStatus(UserStatusEnum userStatusEnum){
        if(UserStatusEnum.DISABLED.equals(userStatusEnum)){
            throw new DisabledAccountException("该帐号已被禁用，请联系管理员！");
        }
        if(UserStatusEnum.LOCKED.equals(userStatusEnum)){
            throw new DisabledAccountException("该帐号已被锁定，请联系管理员！");
        }
        if(UserStatusEnum.UNACTIVATED.equals(userStatusEnum)){
            throw new DisabledAccountException("该帐号未激活，请联系管理员！");
        }

    }


}
